import axios from 'axios'
import {
    CODE_RELOGIN,
    CODE_TOKEN_EXPIRED,
    CODE_SUCCESS,
} from '@/utils/constant'
import {
    addSubscriber,
    refreshAccessToken,
    clearAuthAndRedirect,
} from './refresh'

// export let baseURL = 'http://10.7.162.53:8089'
export let baseURL = 'http://127.0.0.1:5173'

/**
 * process.env.NODE_ENV
 *    production 生产环境
 *        npm run build
 *
 *    development  开发环境
 *        npm run dev
 *
 */
switch (process.env.NODE_ENV) {
    case 'production':
        baseURL = 'http://192.168.1.7:8089'
        break
    case 'development':
        // baseURL = 'http://124.71.63.13:8088'
        baseURL = "http://127.0.0.1:5173";
        break
}

const axiosServer = axios.create({
    baseURL,
    timeout: 3000,
})

//请求拦截器
axiosServer.interceptors.request.use(
    config => {
        // console.log('请求拦截器 config ', config)
        // 设置token到authorization头部
        let token = localStorage.getItem('TOKEN')
        if (token) {
            // console.log('config.headers ',config.headers);
            config.headers['Authorization'] = token
        }
        return config
    },
    error => {
        // 对请求错误做些什么
        return Promise.reject(error)
    }
)

//响应拦截器
axiosServer.interceptors.response.use(
    response => {
        const { config, data } = response

        return new Promise((resolve, reject) => {
            if (data.resultCode === CODE_SUCCESS) {
                resolve(data)
            } else if (data.resultCode === CODE_TOKEN_EXPIRED ) {
                //1.保存当前请求
                addSubscriber(() => {
                    resolve(
                        axiosServer({
                            method: config.method,
                            url: config.url,
                            data: config.data,
                            params: config.params,
                        })
                    )
                })
                //2.刷新token
                refreshAccessToken()
                //3.重新发起请求
            } else if (data.resultCode === CODE_RELOGIN) {
                clearAuthAndRedirect()
            }else{
                reject(data)
            }
        })
        // return response.data
    },
    error => {
        // 对响应错误做点什么
        return Promise.reject(error)
    }
)
export default axiosServer
